package cn.cjj.gulimall.search.service.impl;

import cn.cjj.common.constant.ProductConstant;
import cn.cjj.common.to.es.SkuEsModel;
import cn.cjj.common.utils.Query;
import cn.cjj.common.utils.R;
import cn.cjj.gulimall.search.config.GulimallElasticSearchConfig;
import cn.cjj.gulimall.search.constant.EsConstant;
import cn.cjj.gulimall.search.feign.ProductFeignService;
import cn.cjj.gulimall.search.service.MallSearchService;
import cn.cjj.gulimall.search.vo.AttrRespVo;
import cn.cjj.gulimall.search.vo.SearchParam;
import cn.cjj.gulimall.search.vo.SearchResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author CuiJunJie
 * @create 2021/6/26-16:59
 */
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient client;

    @Autowired
    ProductFeignService productFeignService;


    @Override
    public SearchResult search(SearchParam param) {

        SearchRequest searchRequest = BuildSearchRequest(param);

        SearchResult result = null;
        try {
            SearchResponse searchResponse = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            result = buildSearchResult(param, searchResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    private SearchResult buildSearchResult(SearchParam param, SearchResponse searchResponse) {
        SearchResult result = new SearchResult();

        SearchHits hits = searchResponse.getHits();
        result.setTotal(hits.getTotalHits().value);
        long totalPages = result.getTotal() / EsConstant.PRODUCT_PAGE_SIZE;
        totalPages = result.getTotal() % EsConstant.PRODUCT_PAGE_SIZE == 0 ? totalPages : totalPages + 1;
        result.setTotalPages((int) totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i < totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String esModelString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(esModelString, SkuEsModel.class);
                if (StringUtils.isNotEmpty(param.getKeyword())) {
                    HighlightField skuTitleHighlightField = hit.getHighlightFields().get("skuTitle");
                    String skuTitleHighlight = skuTitleHighlightField.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitleHighlight);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        result.setProducts(skuEsModels);

        Aggregations aggs = searchResponse.getAggregations();
        ParsedStringTerms catelogAgg = aggs.get("catelog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catelogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogName(keyAsString);

            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        ParsedLongTerms brandAgg = aggs.get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            String brandIdStr = bucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brandIdStr));

            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        ParsedNested attrAgg = aggs.get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);

            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attrValueAgg.getBuckets().stream().map(attrValueBucker -> {
                return attrValueBucker.getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> navVos = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.getAttrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    Object attrString = r.get("attr");
                    String attrJsonString = JSON.toJSONString(attrString);
                    AttrRespVo attrRespVo = JSON.parseObject(attrJsonString, AttrRespVo.class);

                    navVo.setNavName(attrRespVo.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                    log.error("调用productFeignService.getAttrInfo（/product/attr/info/{attrId}）失败");
                }

                String replaceQueryString = replaceQueryString(param, attr, "attrs");
                navVo.setLink("http://search.gulimall.com/search.html?" + replaceQueryString);

                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }

//        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
//            SearchResult.NavVo navVo = new SearchResult.NavVo();
//            navVo.setNavName("品牌");
//
//            R r = productFeignService.getBrandInfo(param.getBrandId());
//            if (r.getCode() == 0) {
//                Object brandsObj = r.get("brands");
//                String brandJsonString = JSON.toJSONString(brandsObj);
//                JSONArray brandsJsonArray = JSONArray.parseArray(brandJsonString);
//                List<SearchResult.BrandVo> brands = brandsJsonArray.toJavaList(SearchResult.BrandVo.class);
//                StringBuffer sb = new StringBuffer();
//                String replace = "";
//                for (SearchResult.BrandVo brand : brands) {
//                    sb.append(brand.getBrandName() + ";");
//                    replace = replaceQueryString(param, brand.getBrandId() + "", "brandId");
//                }
//                navVo.setNavValue(sb.toString());
//                navVo.setLink("http://search.gulimall.com/search.html?" + replace);
//
//                List<SearchResult.NavVo> navs = result.getNavs();
//                if (navs == null) {
//                    navs = new ArrayList<>();
//                }
//                navs.add(navVo);
//            } else {
//                log.error("远程调用失败productFeignService.getBrandInfo（/product/brand/infos）");
//            }
//        }


        System.out.println(result);

        return result;
    }

    private String replaceQueryString(SearchParam param, String value, String key) {
        String encodedAttr = "";
        try {
            encodedAttr = URLEncoder.encode(value, "UTF-8");
            encodedAttr = encodedAttr.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String replaceQueryString = param.get_queryString().replace("&" + key + "=" + encodedAttr, "");
        return replaceQueryString;
    }

    private SearchRequest BuildSearchRequest(SearchParam param) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }

        if (param.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catelogId", param.getCatalog3Id()));
        }

        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brandId", param.getBrandId()));
        }

        if (param.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() > 0));
        }

        if (StringUtils.isNotEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");

            /**
             * 100_200
             * _100
             * 100_
             */
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQueryBuilder.gte(s[0]);
                rangeQueryBuilder.lte(s[1]);
            } else if (param.getSkuPrice().startsWith("_")) {
                rangeQueryBuilder.lte(s[0]);
            } else {
                rangeQueryBuilder.gte(s[0]);
            }

            boolQueryBuilder.filter(rangeQueryBuilder);
        }

        if (param.getAttrs() != null && param.getAttrs().size() > 0) {

            for (String attrStr : param.getAttrs()) {
                String[] s = attrStr.split("_");
                System.out.println(Arrays.toString(s));
                String attrId = s[0];
                String[] attrValues = s[1].split(":");

                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
                // warning termQuery and termsQuery
                nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None);

                boolQueryBuilder.filter(nestedQueryBuilder);
            }

        }

        searchSourceBuilder.query(boolQueryBuilder);


        if (StringUtils.isNotEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder sortOrder = "desc".equalsIgnoreCase(s[1]) ? SortOrder.DESC : SortOrder.ASC;
            searchSourceBuilder.sort(s[0], sortOrder);
        }

        searchSourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);

        if (StringUtils.isNotEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brandAgg);

        TermsAggregationBuilder catelogAgg = AggregationBuilders.terms("catelog_agg").field("catelogName").size(50);
        searchSourceBuilder.aggregation(catelogAgg);

        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(attrAgg);

        String dsl = searchSourceBuilder.toString();
        System.out.println(dsl);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }
}
